/**
 * 
 */
package com.dalonedrow.engine.ui.base;

import com.dalonedrow.pooled.PooledStringBuilder;
import com.dalonedrow.pooled.StringBuilderPool;

/**
 * @author Donald
 *
 */
public class GuiComponentLibrary {
	public GuiComponent getComponent(final int id) throws Exception {
		GuiComponent component = null;
		if (id >= 0
				&& id < this.list.length) {
			component = list[id];
		}
		if (component == null) {
			PooledStringBuilder sb =
				StringBuilderPool.getInstance().getStringBuilder();
			sb.append("ERROR! GuiComponentLibrary.getComponent() ");
			sb.append("component with id '");
			sb.append(id);
			sb.append("' was not stored.");
			Exception ex = new Exception(sb.toString());
			sb.returnToPool();
			throw ex;
		}
		return component;
	}
	/** the one and only instance of the <code>GuiComponentLibrary</code> class. */
	private static GuiComponentLibrary	instance;
	/**
	 * GuiComponentLibrary Gives access to the singleton instance of {@link GuiComponentLibrary}.
	 * @return {@link GuiComponentLibrary}
	 */
	public static GuiComponentLibrary getInstance() {
		if (GuiComponentLibrary.instance == null) {
			GuiComponentLibrary.instance = new GuiComponentLibrary();
		}
		return GuiComponentLibrary.instance;
	}
	/** Hidden constructor. */
	private GuiComponentLibrary() { }
	private int nextId = 0;
	public int getNextId() {
		return nextId++;
	}
	private GuiComponent[] list = new GuiComponent[0];
	public void addComponent(final GuiComponent component) {
		if (component.getId() >= list.length) {
			GuiComponent[] dest = new GuiComponent[component.getId() + 1];
			System.arraycopy(list, 0, dest, 0, list.length);
			list = dest;
			dest = null;
		}
		list[component.getId()] = component;
	}
}
